package com.hyou.springboot.base;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import com.hyou.starter.autoconfigure.seq.snowflake.SnowflakeSeq;

/**
 * Service基类
 * 
 * @author FengChangshuo
 * @version 1.0.0 2018-04-04 13:39:55 初始创建
 */
public class BaseService implements InitializingBean {
    
    /**
     * 默认数据源
     */
    @Resource(name = "defaultDataSource")
    private String defaultDataSource;
    
    /**
     * 序列生成器
     */
    @Resource(name = "snowflakeSeq")
    private SnowflakeSeq snowflakeSeq;
    
    @Resource(name = "sqlSessionMap")
    private Map<String, SqlSession> sqlSessionMap;
    
    /**
     * @return 下一个序列值
     */
    public long getNextId() {
        return snowflakeSeq.nextId();
    }
    
    /**
     * 获取连接至默认数据源的SqlMapper对象
     * 
     * @param <T> DAO接口定义类型
     * @param daoClass 要映射成的SQLMapper接口类型
     * @return SQLMapper对应的接口类型
     */
    public <T> T getMapper(Class<T> daoClass) {
        return sqlSessionMap.get(defaultDataSource).getMapper(daoClass);
    }
    
    public <T> T getMapper(Class<T> daoClass, String dataSource) {
        return sqlSessionMap.get(dataSource).getMapper(daoClass);
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.sqlSessionMap, "sqlSessionMap不能为空");
        Assert.notNull(this.snowflakeSeq, "snowflakeSeq不能为空");
    }

    public void setDefaultDataSource(String defaultDataSource) {
        this.defaultDataSource = defaultDataSource;
    }

    /**
     * @return the sqlSessionMap
     */
    public Map<String, SqlSession> getSqlSessionMap() {
        return this.sqlSessionMap;
    }

    /**
     * @param sqlSessionMap the sqlSessionMap to set
     */
    public void setSqlSessionMap(Map<String, SqlSession> sqlSessionMap) {
        this.sqlSessionMap = sqlSessionMap;
    }
    
}
